package li.webqq.api;

import java.util.List;
import java.util.Map;

import li.http.Response;
import li.webqq.model.Message;
import li.webqq.util.JsonUtil;
import li.webqq.util.MapUtil;

import org.apache.log4j.Logger;

/**
 * @author 明伟
 */
public class Poll2Response extends Response {
    private static final Logger logger = Logger.getLogger(Poll2Response.class);

    private Message message;

    public Message getMessage() {
        if (null == this.message) {
            logger.info("Poll2Response getMessage = " + super.getBody());
            Map map = (Map) JsonUtil.fromJson(super.getBody());
            if (null != map) {
                List<Map> result = (List<Map>) map.get("result");
                this.message = this.getMessage(result);
            }
        }
        return this.message;
    }

    private Message getMessage(List<Map> result) {
        if (null == result) {
            return null;
        }
        Map result_0 = result.get(0);
        if (null == result_0) {
            return null;
        }
        Map value = (Map) result_0.get("value");
        Message message = MapUtil.parse(Message.class, value);
        List<Object> content = (List<Object>) value.get("content");
        String text = "";
        if (null != content) {
            for (Object each : content) {
                if (each instanceof String) {// 不是String则是表情，字体等信息，暂未处理
                    text += (String) each;
                }
            }
        }
        if (!text.isEmpty()) {
            message.setContent(text);
        }
        message.setPoll_type(result_0.get("poll_type") + "");
        return message;
    }

    /**
     * 处理返回信息的接口
     */
    public interface MessageHandler {
        public void hand(Poll2Response response);
    }
}